<?php
//require_once XOOPS_ROOT_PATH ."/class/xoopstree.php" ;
require_once realpath(dirname(__FILE__)) . '/../include/functions.php';

class linksCategoriesClass/* extends XoopsTree*/
{
//	var $db ;
	var $table ;
	var $mydirname ;

	//fields
	var $cid       = 'cid' ;
	var $pid       = 'pid' ;
	var $order     = 'corder' ;
	var $title     = 'title' ;
	var $imgurl    = 'imgurl' ;
	var $is_mobile = FALSE;

	function linksCategoriesClass( $mydirname )
	{
		$db =& Database::getInstance();
	//	$this->db =& Database::getInstance();
		$this->mydirname = $mydirname;
		$this->table = $db->prefix($mydirname . '_cat');
	//	$this->table = $this->db->prefix($mydirname . '_cat');
	//	parent::XoopsTree($table, $this->cid, $this->pid);
	}

	function update($cid=0)
	{
		$rtn = false;
		if( $cid>0 && $this->getCategory($cid) ){
			$postdata = $this->getPOST();
			if( !empty($postdata[$this->title]) || $postdata[$this->pid]!=$cid ){
				$db =& Database::getInstance();
				$sql = "UPDATE ". $this->table ." SET ";
				$sql.= $this->pid ."='". $postdata[$this->pid] ."' , " ;
				$sql.= $this->title ."='". mysql_real_escape_string($postdata[$this->title]) ."' , " ;
				$sql.= $this->order ."='". $postdata[$this->order] ."' , " ;
				$sql.= $this->imgurl ."='". mysql_real_escape_string($postdata[$this->imgurl]) ."'" ;
				$sql.= " WHERE cid='$cid'" ;
				$db->query($sql) or die( "DB Error: update category" );
			//	$this->db->query($sql) or die( "DB Error: update category" );
				$rtn = true;
			}
		}
		return $rtn ;
	}

	function insert()
	{
		$rtn = false;
		$postdata = $this->getPOST();
		if( !empty($postdata[$this->title]) ){
			$db =& Database::getInstance();
			$sql = "INSERT INTO ". $this->table ." SET " ;
			$sql.= $this->pid ."='". $postdata[$this->pid] ."' , " ;
			$sql.= $this->title ."='". mysql_real_escape_string($postdata[$this->title]) ."' , " ;
			$sql.= $this->order ."='". $postdata[$this->order] ."' , " ;
			$sql.= $this->imgurl ."='". mysql_real_escape_string($postdata[$this->imgurl]) ."'" ;
			$db->query($sql) or die( "DB Error: insert category" );
		//	$this->db->query($sql) or die( "DB Error: insert category" );
			$rtn = true;
		}
		return $rtn;
	}


	function delete( $cid=0 )
	{
		$rtn = FALSE;
		if( $cid > 0 && $this->getCategory($cid) ){
			$delete_cids = $this->getAllChildId($cid);
			$delete_cids[] = $cid ;
			$rtn = $this->deleteCats($delete_cids);
		}
		return $rtn ;
	}

	function deleteCats($cids)
	{
		$rtn = FALSE;
		if( is_array($cids) ){
			$db =& Database::getInstance();
			$whr = '';
			foreach( $cids as $id ){
				if( $whr!='' ) $whr.= " OR ";
				$whr.= " cid=$id ";
			}
			$sql = "DELETE FROM ". $this->table ." WHERE $whr";
			$db->query($sql) or die( "DB Error: delete category" );
		//	$this->db->query($sql) or die( "DB Error: delete category" );
			$rtn = TRUE ;
		}
		return $rtn ;
	}


	function getPOST()
	{
		$myts =& MyTextSanitizer::getInstance();
		$ret = array();
		$ret[$this->pid] = isset($_POST[$this->pid]) ? intval($_POST[$this->pid]) : 0 ;
		$ret[$this->order] = isset($_POST[$this->order]) ? intval($_POST[$this->order]) : 0 ;
		$ret[$this->cid] = isset($_POST[$this->cid]) ? intval($_POST[$this->cid]) : 0 ;
		$ret[$this->title] = isset($_POST[$this->title]) ? $myts->stripSlashesGPC($_POST[$this->title]) : "" ;
		$ret[$this->imgurl] = isset($_POST[$this->imgurl]) ? $myts->stripSlashesGPC($_POST[$this->imgurl]) : "" ;
		return $ret;
	}

	function getCategory($cid=0)
	{
		$row = false;
		if($cid>0){
			$db =& Database::getInstance();
			$sql = "SELECT * FROM ".$this->table." WHERE ".$this->cid."=$cid";
			$row = $db->fetchArray($db->query($sql));
		//	$row = $this->db->fetchArray( $this->db->query($sql) );
		}
		return $row ;
	}

	//----------------------------------------------------------------------------------

	function getAllcatKeyCid( $order='',$pid=0 , $return_array=array() )
	{
		$db =& Database::getInstance();
		$whr = $this->pid."=".$pid ;
		$odr = ( $order!='' ) ? " ORDER BY $order " : "" ;
		$sql = "SELECT * FROM ".$this->table . " WHERE $whr $odr" ;
		$result = $db->query( $sql );
	//	$result = $this->db->query( $sql );
		$count = $db->getRowsNum($result);
	//	$count = $this->db->getRowsNum($result);
		if ( $count == 0 ) {
			return $return_array ;
		}
		while( $row = $db->fetchArray($result) ){
	//	while( $row = $this->db->fetchArray($result) ){
			$arr = array();
			$return_array[$row[$this->cid]] = htmlspecialchars($row[$this->title], ENT_QUOTES, _CHARSET) ;
			$return_array = $this->getAllcatKeyCid( $order , $row[$this->cid] , $return_array ) ;
		}
	//	var_dump($return_array);
		return $return_array ;
	}

	//TODO
	//generates path from the root id to a given id($sel_id)
	function getPathFromId($sel_id, $path="")
	{
		global $myurl ;
		$db =& Database::getInstance();
	//	var_dump($this->myurl);
	//	var_dump($myurl);
		$result = $db->query("SELECT ".$this->pid.", ".$this->title." FROM ".$this->table." WHERE ".$this->cid."=$sel_id");
	//	$result = $this->db->query("SELECT ".$this->pid.", ".$this->title." FROM ".$this->table." WHERE ".$this->cid."=$sel_id");
		if ($db->getRowsNum($result) == 0) {
	//	if ( $this->db->getRowsNum($result) == 0 ) {
			//$path = substr($path, 1);
			return $path;
		}
		list($parentid,$name) = $db->fetchRow($result);
	//	list($parentid,$name) = $this->db->fetchRow($result);
	//	var_dump($parentid);var_dump($name);
		$name = htmlspecialchars($name, ENT_QUOTES, _CHARSET);
		$path = $this->_make_category_url($sel_id, $name, $path);
		if ( $parentid == 0 ) {
			$path = substr($path, 1);
			$path = $this->_adjust_path($path);
			return $path;
		}
		$path = $this->getPathFromId($parentid, $path);
		return $path;
	}

	function _adjust_path($path)
	{
		$path = str_replace(">/<","> <img src='". XOOPS_URL .'/modules/'. $this->mydirname ."/images/arrow.gif' board='0' alt='' /> <",$path);

		return $path;
	}

	function _make_category_url($sel_id, $name, $path)
	{
		//Module Config
		$module_handler =& xoops_gethandler('module');
		$xoopsModule =& $module_handler->getByDirname($this->mydirname);
		$config_handler =& xoops_gethandler('config');
		$module_config =& $config_handler->getConfigsByCat(0, $xoopsModule->getVar('mid'));

		$uri = XOOPS_URL . '/';

		if ($module_config['url_approach'] < 3) {
			$uri .= 'modules/';
		}
		$uri .= $this->mydirname . '/' ;

		if ($module_config['url_approach'] > 0) {
			//segment approach
			if ($module_config['url_approach'] == 1) {
				$uri .= 'index.php/';
			}
			$uri .= 'category/index/'. $sel_id;
			if (!empty($module_config['url_suffix'])) {
				$uri .= $module_config['url_suffix'];
			}
		} else {
			//query approach
			$uri .= 'index.php?c=category&amp;cid='. $sel_id ;
		}
		$path_text = "/<a href='$uri'>".$name."</a>".$path."";
		return $path_text;
	}

	//makes a nicely ordered selection box
	//$preset_id is used to specify a preselected item
	//set $none to 1 to add a option with value 0
	function makeMySelBox($order="", $preset_id=0, $none=0, $sel_name="", $onchange="", $elm_id="", $multiple=1)
	{
		$db =& Database::getInstance();

		$selector_html = '';

		if ( $sel_name == "" ) {
			$sel_name = $this->cid;
		}
		$myts =& MyTextSanitizer::getInstance();
		$selector_html .= "<select name='".$sel_name."'";
		if( $onchange != "" ){
			$selector_html .= " onchange='".$onchange."'";
		}
		if( $elm_id != "" ){
			$selector_html .= " id='". $elm_id ."' " ;
		}
		if( $multiple==1 ){
			$selector_html .= " multiple='multiple' " ;
		}
		$selector_html .= ">\n";
		$sql = "SELECT ".$this->cid.", ".$this->title." FROM ".$this->table." WHERE ".$this->pid."=0";
		if ( $order != "" ) {
			$sql .= " ORDER BY $order";
		}
		$result = $db->query($sql);
	//	$result = $this->db->query($sql);
		if ( $none ) {
			$selector_html .= "<option value='0'>----</option>\n";
		}
		while ( list($catid, $name) = $db->fetchRow($result) ) {
	//	while ( list($catid, $name) = $this->db->fetchRow($result) ) {
			$sel = "";
			if( is_array($preset_id) ){
				if ( in_array($catid,$preset_id) ){
					$sel = " selected='selected'";
				}
			}else{
				if ( $catid == $preset_id ){
					$sel = " selected='selected'";
				}
			}
			$selector_html .= "<option value='$catid'$sel>".$myts->makeTboxData4Show($name)."</option>\n";
			$sel = "";
			$arr = $this->getChildTreeArray($catid, $order);
			foreach ( $arr as $option ) {
				$option['prefix'] = str_replace(".","--",$option['prefix']);
				$catpath = $option['prefix']."&nbsp;".$myts->makeTboxData4Show($option[$this->title]);
				if( is_array($preset_id) ){
					if( in_array($option[$this->cid],$preset_id) ){
						$sel = " selected='selected'";
					}
				}else{
					if( $option[$this->cid] == $preset_id ){
						$sel = " selected='selected'";
					}
				}
				$selector_html .= "<option value='".$option[$this->cid]."'$sel>$catpath</option>\n";
				$sel = "";
			}
		}
		$selector_html .= "</select>\n";

		return $selector_html;
	}

	function getCategories($cid = 0)
	{
		$cid = intval($cid);
		$firstCids = $this->getFirstChild($cid,"corder,cid");

		$temp_cat = array() ;
		foreach( $firstCids as $myrow ) {
			$imgurl = '';
			if ( !empty($myrow['imgurl']) && $myrow['imgurl'] != "http://" ){
				$imgurl = links_urlCheckReplace( $myrow['imgurl'] ) ;
				$imgurl = htmlspecialchars($imgurl, ENT_QUOTES, _CHARSET);
			}
			$totallink = $this->_get_TotalItems($myrow['cid'], 1, TRUE);
			$arr = array();
			$arr = $this->getFirstChild($myrow['cid'], "corder,cid");//title
			$subcount = 0;
			$subcategories = array();
			foreach( $arr as $ele ){
				if ($subcount > 5 && ! $this->is_mobile) {
					$subcategories[] = array('cid' => 0, 'title' => "...");
					break;
				}
				$subcategories[] = array('cid' => $ele['cid'], 'title' => htmlspecialchars($ele['title'], ENT_QUOTES, _CHARSET));
				$subcount++ ;
			}

			$temp_cat[] = array(
				'image'         => $imgurl ,
				'id'            => intval($myrow['cid']) ,
				'title'         => htmlspecialchars($myrow['title'], ENT_QUOTES, _CHARSET) ,
				'subcategories' => $subcategories ,
				'totallink'     => $totallink 
			) ;
		}

		return $temp_cat ;
	}

	function _get_TotalItems($sel_id, $status = "", $dist = FALSE )
	{
		$arr = $this->getAllChildId($sel_id);

		$count = 0;
		if ( $dist ){ //Single Count
			$arr[] = $sel_id ;
			$count = $this->getItemsNum( $arr, $status );
		} else { //Repetition Count
			$count = $this->getItemsNum( $sel_id, $status );
			for($i=0;$i<count($arr);$i++){
				$subcount = $this->getItemsNum( $arr[$i], $status );
				$count += $subcount ;
			}
		}

		return $count;
	}

	function getItemsNum($sel_id, $status = "")
	{
		$db =& Database::getInstance();
		$table_links = $db->prefix($this->mydirname . '_links');
	//	$table_links = $this->db->prefix($this->mydirname . '_links');
		if (is_array($sel_id)) {
			$cidwhere = "" ;
			for( $i=0 ; $i<count($sel_id); $i++ ){
				if( $cidwhere != "" ) $cidwhere .= " OR " ;
				$cidwhere .= " cid LIKE '%[". $sel_id[$i] ."]%'" ;
			}
		} else {
			$cidwhere = "cid LIKE '%[".$sel_id."]%'";
		}
		$sql = "SELECT count(*) FROM $table_links WHERE ( $cidwhere ) AND date<". time();
		if($status != "") $sql .= " AND status>=$status";
		$result = $db->query($sql);
	//	$result = $this->db->query($sql);
		list($count) = $db->fetchRow($result);
	//	list($count) = $this->db->fetchRow($result);

		return $count;
	}


	function setMobile($mobile = FALSE)
	{
		$this->is_mobile = $mobile;
	}

// ------------------------------------------------
	function getFirstChild($sel_id, $order="")
	{
		$db =& Database::getInstance();
		$arr =array();
		$sql = "SELECT * FROM ".$this->table." WHERE ".$this->pid."=".$sel_id."";
		if ( $order != "" ) {
			$sql .= " ORDER BY $order";
		}
		$result = $db->query($sql);
		$count = $db->getRowsNum($result);
		if ( $count==0 ) {
			return $arr;
		}
		while ( $myrow = $db->fetchArray($result) ) {
			array_push($arr, $myrow);
		}
		return $arr;
	}

	//returns an array of ALL child ids for a given id($sel_id)
	function getAllChildId($sel_id, $order="", $idarray = array())
	{
		$db =& Database::getInstance();
		$sql = "SELECT ".$this->cid." FROM ".$this->table." WHERE ".$this->pid."=".$sel_id."";
		if ( $order != "" ) {
			$sql .= " ORDER BY $order";
		}
		$result=$db->query($sql);
		$count = $db->getRowsNum($result);
		if ( $count==0 ) {
			return $idarray;
		}
		while ( list($r_id) = $db->fetchRow($result) ) {
			array_push($idarray, $r_id);
			$idarray = $this->getAllChildId($r_id,$order,$idarray);
		}
		return $idarray;
	}

	function getAllChild($sel_id=0,$order="",$parray = array())
	{
		$db =& Database::getInstance();
		$sql = "SELECT * FROM ".$this->table." WHERE ".$this->pid."=".$sel_id."";
		if ( $order != "" ) {
			$sql .= " ORDER BY $order";
		}
		$result = $db->query($sql);
		$count = $db->getRowsNum($result);
		if ( $count == 0 ) {
			return $parray;
		}
		while ( $row = $db->fetchArray($result) ) {
			array_push($parray, $row);
			$parray=$this->getAllChild($row[$this->cid],$order,$parray);
		}
		return $parray;
	}

	function getChildTreeArray($sel_id=0,$order="",$parray = array(),$r_prefix="")
	{
		$db =& Database::getInstance();
		$sql = "SELECT * FROM ".$this->table." WHERE ".$this->pid."=".$sel_id."";
		if ( $order != "" ) {
			$sql .= " ORDER BY $order";
		}
		$result = $db->query($sql);
		$count = $db->getRowsNum($result);
		if ( $count == 0 ) {
			return $parray;
		}
		while ( $row = $db->fetchArray($result) ) {
			$row['prefix'] = $r_prefix.".";
			array_push($parray, $row);
			$parray = $this->getChildTreeArray($row[$this->cid],$order,$parray,$row['prefix']);
		}
		return $parray;
	}

}
